const fs = require('fs');
const path = require('path');

class _Load {

  /**
   * 文件加载
   * @param {String} targetPath 
   * @param {Function} transFunc
   * @param {Array} ignore ['']
   * @param {Array} suffixs ['']
   * @return {Object}
   */
  loadFileSync(
    targetPath,
    transFunc = this.origin,
    ignore = [],
    suffixs = _Load.suffixDomain,
    callBack
  ) {
    const Module = {};
    try {
      const files = fs.readdirSync(targetPath);
      for (const file of files) {
        const index = file.indexOf('.'),
          suffix = file.substring(index + 1);
        const stat = fs.statSync(`${targetPath}/${file}`);
        if (!ignore.some(iname => iname.indexOf(file) !== -1) &&
          stat.isFile() &&
          suffixs.includes(suffix)) {
          const filePath = file.replace(path.extname(file), '');
          const name = file.substring(0, index);
          const loadContent = require(path.normalize(
            `${targetPath}/${filePath}`
          ));
          Module[transFunc(name)] = callBack ? callBack(loadContent) :
            loadContent;
        }
      }
    } catch (error) {
      console.error(`load file error: ${error.stack}`);
      throw error;
    }
    return Module;
  }

  /**
   * 首字母大写,下划线转驼峰
   * @param {String} name 
   * @return {String} 
   */
  firstUpper(name) {
    name = name.toString();
    return name.substring(0, 1).toUpperCase() +
      name.substring(1).replace(
        /_[a-z]/g, str => str.substring(1).toUpperCase()
      );
  }

  /**
   * 首字母小写,下划线转驼峰
   * @param {String} name 
   * @return {String} 
   */
  firstLower(name) {
    name = name.toString();
    return name.substring(0, 1).toLowerCase() +
      name.substring(1).replace(
        /_[a-z]/g, str => str.substring(1).toUpperCase()
      );
  }

  /**
   * 字母全大写
   * @param {String} name 
   * @return {String}
   */
  allUpper(name) {
    name = name.toString();
    return name.toUpperCase();
  }

  /**
   * 字母全小写
   * @param {String} name 
   * @return {String}
   */
  allLower(name) {
    name = name.toString();
    return name.toLowerCase();
  }

  /**
   * @param {String} name 
   * @return {String}
   */
  origin(name) {
    return name;
  }

}

// 文件加载后缀白名单
_Load.suffixDomain = ['js', 'json', 'node'];


module.exports = new _Load();